//
//  NoReadViewController.m
//  lsOA
//
//  Created by 蓝水软件 on 16/8/16.
//  Copyright © 2016年 苏州蓝水有限公司. All rights reserved.
//

#import "NoReadViewController.h"
#import "NoNetWorkingView.h"
#import "NoReadTableViewCell.h"
#import "MyMessageViewController.h"
#import "MeetViewController.h"
#import "DocReviewViewController.h"
#import "WorkTaskViewController.h"
#import "MyInformationViewController.h"
#import "MyCreatApprovalViewController.h"
#import "InformationViewController.h"


@interface NoReadViewController ()<UITableViewDelegate,UITableViewDataSource>{
    UITableView *table;
    NoNetWorkingView *netWorkView;
    NSMutableArray *newsArray;
    NSMutableArray *meetArray;
    NSMutableArray *taskArray;
    NSMutableArray *approvalArray;
    
    NSMutableDictionary *dataSource; //总数据
    NSString *sevenDayAgoString;
    NSString *nowDayString;
    
    NSArray *isShow;
    UIButton *button;
}
@property (nonatomic,strong) YALSunnyRefreshControl *sunnyRefreshControl;
@end

@implementation NoReadViewController

- (void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showNoNetWorkTag:) name:@"noNetWork" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"noNetWork" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc]init];
    [dateFormater setDateFormat:@"yyyy-MM-dd"];
    NSDate *nowDate = [NSDate date];
    nowDayString = [dateFormater stringFromDate:nowDate];
    NSTimeInterval time = 60*60*24;
    NSDate *sevenAgo = [nowDate dateByAddingTimeInterval:-time*7];
    sevenDayAgoString = [dateFormater stringFromDate:sevenAgo];
    dataSource = [[NSMutableDictionary alloc]init];
    [self setUI];
    [self getDataNew];
    isShow = @[@"1",@"1",@"1",@"1"];
}


//公告
- (void)getDataNew{
    
    NSString *ashx = @"/Server/NewsHandlerNew.ashx";
    NSDictionary *dic = @{@"act":@"getl",@"dates":[NSDate todayAddDaysToString:-7],@"ntype":@"0",@"uname":[UserInfo getUserName],@"upwd":[UserInfo getPassWord]};
    [httpPostRequest getDataByPostAshx:ashx and:dic withFinishBlock:^(id model, NSError *error) {
        if (error == nil) {
            NSString *code = [NSString stringWithFormat:@"%@",[model objectForKey:@"code"]];
            if ([code isEqualToString:@"0"]) {
                NSLog(@"数据：%@",model);
                NSArray *tempArray = model[@"data"];
                newsArray = [NSMutableArray array];
                for (NSDictionary *dic in tempArray) {
                    if ([dic[@"nVS"] intValue] == 0) {
                        [newsArray addObject:dic];
                    }
                }
                [dataSource setObject:newsArray forKey:@"0"];
                [self getDataMeet];
                
            }else{
                [XHToast showCenterWithText:[model objectForKey:@"msg"]];
            }
        }else{
            [XHToast showBottomWithText:@"请求失败"];
        }
    }];
    
}

//会议
- (void)getDataMeet{
    
    NSString *ashx = @"/Server/MeetingHandler.ashx";
    NSDictionary *dic = @{@"act":@"getm",@"dates":sevenDayAgoString,@"verify":@"all",@"uname":[UserInfo getUserName],@"upwd":[UserInfo getPassWord]};
    [httpPostRequest getDataByPostAshx:ashx and:dic withFinishBlock:^(id model, NSError *error) {
        if (error == nil) {
            NSString *code = [NSString stringWithFormat:@"%@",[model objectForKey:@"code"]];
            if ([code isEqualToString:@"0"]) {
                NSLog(@"会议:%@",model);
                NSArray *tempArray = model[@"data"];
                meetArray = [NSMutableArray array];
                for (NSDictionary *dic in tempArray) {
                    if ([dic[@"mVS"] intValue] == 0) {
                        [meetArray addObject:dic];
                    }
                }
                [dataSource setObject:meetArray forKey:@"1"];
                [self getDataApproval];
            }else{
                [XHToast showCenterWithText:[model objectForKey:@"msg"]];
            }
        }else{
            [XHToast showBottomWithText:@"请求失败"];
        }
    }];
    
    
}

//审批
- (void)getDataApproval{
    NSString *ashx = @"/Server/FlowsHandler.ashx";
    NSDictionary *dic = @{@"act":@"getf",@"uname":[UserInfo getUserName],@"upwd":[UserInfo getPassWord]};
    [httpPostRequest getDataByPostAshx:ashx and:dic withFinishBlock:^(id model, NSError *error) {
        if (error == nil) {
            NSString *code = [NSString stringWithFormat:@"%@",[model objectForKey:@"code"]];
            if ([code isEqualToString:@"0"]) {
                NSLog(@"审批:%@",model);
                NSArray *tempArray = model[@"data"];
                approvalArray = [NSMutableArray array];
                for (NSDictionary *dic in tempArray) {
                    if ([dic[@"notDeal"] intValue] == 1) {
                        [approvalArray addObject:dic];
                    }
                }
                [dataSource setObject:approvalArray forKey:@"2"];
                [self getDataTask];
                
            }else{
                [XHToast showCenterWithText:[model objectForKey:@"msg"]];
            }
        }else{
            [XHToast showBottomWithText:@"请求失败"];
        }
    }];
    
    
    
}
//任务
- (void)getDataTask{
    
    NSString *ashx = @"/Server/TaskHandler.ashx";
    NSDictionary *dic = @{@"act":@"getl",@"uname":[UserInfo getUserName],@"upwd":[UserInfo getPassWord]};
    [httpPostRequest getDataByPostAshx:ashx and:dic withFinishBlock:^(id model, NSError *error) {
        if (error == nil) {
            NSString *code = [NSString stringWithFormat:@"%@",[model objectForKey:@"code"]];
            if ([code isEqualToString:@"0"]) {
                NSLog(@"任务数据:%@",model[@"data"]);
                NSArray *tempArray = model[@"data"];
                taskArray = [NSMutableArray array];
                for (NSDictionary *dic in tempArray) {
                    if ([dic[@"Status"] intValue] == 1) {
                        [taskArray addObject:dic];
                    }
                }
                [dataSource setObject:taskArray forKey:@"3"];
                [self performSelector:@selector(endAnimationHandle) withObject:nil afterDelay:0.0f];
                [table reloadData];
            }else{
                [XHToast showCenterWithText:[model objectForKey:@"msg"]];
            }
        }else{
            [XHToast showBottomWithText:@"请求失败"];
        }
    }];
    
    
}




- (void)setUI{
    self.view.backgroundColor = [UIColor whiteColor];
    UIImageView *backImage = [[UIImageView alloc]init];
    backImage.image = [UIImage imageNamed:@"主界面(背景)"];
    backImage.backgroundColor = [UIColor redColor];
    backImage.frame = CGRectMake(0, 60, KSWidth, KSHeight-60);
    [self.view addSubview:backImage];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSWidth, KSHeight-120) style:UITableViewStylePlain];
    table.backgroundColor = [UIColor whiteColor];
    table.delegate = self;
    table.dataSource = self;
    [self setupRefreshControl];
    [self.view addSubview:table];
    
    netWorkView = [[NoNetWorkingView alloc]init];
    [self.view addSubview:netWorkView];
    [netWorkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.width.equalTo(table);
        make.height.mas_equalTo(0);
    }];
    [netWorkView setHidden:YES];
    
    
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger num = 0;
    if ([isShow[section] isEqualToString:@"1"]) {
        switch (section) {
            case 0:{
                num = newsArray.count;
            }
                break;
            case 1:{
                num = meetArray.count;
            }
                break;
            case 2:{
                num = approvalArray.count;
            }
                break;
            case 3:{
                num = taskArray.count;
            }
                break;
        }
        
    }
    return num;
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 4;
}

- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return @" ";
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 40*FitSize;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *under = [UIView new];
    under.backgroundColor = [UIColor colorWithHexString:@"#ecf0f4"];
    under.bounds = CGRectMake(0, 0, KSWidth, 40*FitSize);
    NSInteger num = 0;
    NSString *title = @"";
    switch (section) {
        //公文通知
        case 0:{
            num = newsArray.count;
            title = [title stringByAppendingString:@"(最近没有您未查看的通知)"];
        }
            break;
        //会议通知
        case 1:{
            num = meetArray.count;
            title = [title stringByAppendingString:@"(最近没有您需要参与的会议)"];
        }
            break;
        //公文审批
        case 2:{
            num = approvalArray.count;
            title = [title stringByAppendingString:@"(最近没有您需要审批的公文)"];
          
        }
            break;
        //任务进程
        case 3:{
            num = taskArray.count;
            title = [title stringByAppendingString:@"(最近没有您需要执行的任务)"];
        }
            break;
        default:
            break;
    }
    
    NSArray *array = @[@"待读通知",@"待参与会议",@"待审批公文",@"待执行任务"];
    
    UIView *leftView = [UIView new];
    leftView.layer.cornerRadius = 2;
    [under addSubview:leftView];
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10*FitSize);
        make.width.mas_equalTo(5*FitSize);
        make.height.mas_equalTo(25*FitSize);
        make.centerY.equalTo(under);
    }];

    if (num == 0) {
        leftView.backgroundColor = [UIColor colorWithHexString:@"#08663c"];
        
//        UILabel *techlabel = [UILabel new];
//        [under addSubview:techlabel];
//        techlabel.font = [UIFont systemFontOfSize:10*FitSize];
//        [techlabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.mas_equalTo(30*FitSize);
//            make.bottom.equalTo(under);
//        }];
//        techlabel.text = title;
//        techlabel.textColor = [UIColor colorWithHexString:@"#08663c"];
    }else{
        leftView.backgroundColor = [UIColor colorWithHexString:@"#e20517"];
    }

    UIButton *titleLabel = [UIButton buttonWithType:UIButtonTypeCustom];
    [titleLabel setTitle:array[section] forState:UIControlStateNormal];
    titleLabel.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    titleLabel.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [titleLabel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    titleLabel.tag = 2000+section;
    [titleLabel addTarget:self action:@selector(nessList:) forControlEvents:UIControlEventTouchUpInside];
    [under addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(under);
        make.left.equalTo(leftView.mas_right).offset(3);
        make.width.mas_equalTo(KSWidth);
        make.height.mas_equalTo(25*FitSize);
    }];
    
    UIImageView *rightTag = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right"]];
    [under addSubview:rightTag];
    [rightTag mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-5);
        make.size.mas_equalTo(CGSizeMake(15*FitSize, 20*FitSize));
        make.centerY.equalTo(under);
    }];
    if (section == 2) {
        //查看我的申请
        UIButton *myApply = [UIButton buttonWithType:UIButtonTypeCustom];
        [under addSubview:myApply];
        myApply.titleLabel.font = [UIFont systemFontOfSize:10*FitSize];
        [myApply setTitle:@"我的申请" forState:UIControlStateNormal];
        [myApply setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        myApply.layer.borderWidth = 1.0;
        myApply.layer.borderColor = [UIColor lightGrayColor].CGColor;
        myApply.layer.cornerRadius = 2.0;
        [myApply mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-30*FitSize);
            make.width.mas_equalTo(80*FitSize);
            make.height.mas_equalTo(25*FitSize);
            make.centerY.equalTo(under);
        }];
        [myApply addTarget:self action:@selector(pushToMyApply) forControlEvents:UIControlEventTouchUpInside];
    }

   
    return under;
}

- (void)pushToMyApply{
    MyCreatApprovalViewController *myApproval = [[MyCreatApprovalViewController alloc] init];
    myApproval.fromView = @"3";
    myApproval.listType = @"0";
    [self.navigationController pushViewController:myApproval animated:YES];
    
}

//点击进入列表
- (void)nessList:(UIButton *)sender{
    if (sender.tag-2000+1 == 2) {
        MyInformationViewController *viewController = [[MyInformationViewController alloc]init];
        viewController.title = @"会议管理";
        viewController.fromView = [NSString stringWithFormat:@"%@",@(sender.tag - 2000+1)];
        [self.navigationController pushViewController:viewController animated:YES];
        return;
    }
    
    
    InformationViewController *ViewController = [[InformationViewController alloc]init];
    ViewController.fromView = [NSString stringWithFormat:@"%@",@(sender.tag - 2000+1)];
    [self.navigationController pushViewController:ViewController animated:YES];
    
    
    
}

//展开表格组
- (void)btnOpenList:(UIButton *)sender{
    
    NSInteger index = sender.tag - 1000;
    NSString *value = isShow[index];
    value = [value isEqualToString:@"1"]? @"0":@"1";
    
    NSMutableArray *tempArray = [NSMutableArray array];
    
    for (int i = 0; i < isShow.count; i++) {
        if (i == index) {
            [tempArray addObject:value];
        }else{
            [tempArray addObject:isShow[i]];
        }
    }
    isShow = [tempArray copy];
    
    
    [table reloadData];
    
    
    
}

/**
 *  每行高度
 *
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70*FitSize;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellID = @"CellID";
    NoReadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (!cell) {
        cell = [[NoReadTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    NSString *key = [NSString stringWithFormat:@"%ld",(long)indexPath.section];
    NSArray *array = [dataSource objectForKey:key];
    [cell setValueWithDic:array[indexPath.row] section:indexPath.section];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *section = [NSString stringWithFormat:@"%ld",(long)indexPath.section];
    NSArray *array = dataSource[section];
    NSDictionary *dic = array[indexPath.row];
    [self pushView:section NSDic:dic];
}

/**
 *  推送界面 － 响应表格点击事件
 *
 *  @param fromView 用于区别从哪个界面点击过来的
 *  @param type     用于区别界面具体详情的类型
 *  @param detailDic     详情界面需要显示的数据
 */
- (void)pushView:(NSString *)section  NSDic:(NSDictionary *)detailDic {
    
    switch ([section intValue]) {
        case 0:{
            MyMessageViewController *myMessage = [[MyMessageViewController alloc]init];
            myMessage.dic = detailDic;
            [self.navigationController pushViewController:myMessage animated:YES];
        }
            break;
        case 1:{
            MeetViewController *meet = [[MeetViewController alloc]init];
            meet.dic = detailDic;
            [self.navigationController pushViewController:meet animated:YES];
        }
            break;
        case 2:{
            DocReviewViewController *docReview = [[DocReviewViewController alloc]init];
            docReview.dic = detailDic;
            [self.navigationController pushViewController:docReview animated:YES];
        }
            break;
        case 3:{
            WorkTaskViewController *workTask = [[WorkTaskViewController alloc]init];
            workTask.dic = detailDic;
            [self.navigationController pushViewController:workTask animated:YES];
        }
            break;
            
    }
}


//根据网络状态观察者传来的值进行判断，如果为－1就显示控件
- (void)showNoNetWorkTag:(NSNotification *)sender{
    NSString *isConnection = [sender object];
    if ([isConnection isEqualToString:@"-1"]) {
        [netWorkView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(30);
        }];
    }else{
        //有网络，隐藏控件，并重新发送请求数据
        [netWorkView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
    }
}

# pragma mark - YALSunyRefreshControl methods
//初始化刷新控件
-(void)setupRefreshControl{
    self.sunnyRefreshControl = [YALSunnyRefreshControl new];
    [self.sunnyRefreshControl addTarget:self
                                 action:@selector(sunnyControlDidStartAnimation)
                       forControlEvents:UIControlEventValueChanged];
    [self.sunnyRefreshControl attachToScrollView:table];
}


//刷新执行事件 其实他应该算重新加载数据
-(void)sunnyControlDidStartAnimation{
    
    [self getDataNew];
    
}
//开始刷新动画
- (void)beginAnimationHandle{
    [self.sunnyRefreshControl beginRefreshing];
    
}
//结束刷新动画
-(void)endAnimationHandle{
    [self.sunnyRefreshControl endRefreshing];
}
@end
